﻿using Learn.Infraestrutura.Attr;
using Learn.Infraestrutura.Dto.Request;
using Learn.Infraestrutura.Dto.Response;
using Learn.Infraestrutura.Dto.Response.Login;
using Learn.Infraestrutura.EFCore;
using Learn.Infraestrutura.IOC;
using Learn.Infraestrutura.Tools;
using Learn.Service.Interface;
using Microsoft.Extensions.Configuration;
using MySqlX.XDevAPI.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.WebSockets;
using System.Text;

namespace Learn.Service.Instance
{
    [Inject_]
    public class Login_Service : Base_Service,I_Login_Service
    {
        private readonly Login_IOC _login_IOC;
        private readonly IConfiguration _configuration;

        public Login_Service(IConfiguration configuration, Login_IOC login_IOC)
        {
            _login_IOC = login_IOC;
            _configuration = configuration;
        }

        /// <summary>
        /// 获取登录历史
        /// </summary>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <param name="uid"></param>
        /// <returns></returns>
        public Api_Result Get_Log_History(int page, int limit, string uid)
        {
            var iq = _login_IOC._sys_Login_Log_EFCore.QueryAll(out int total, page, limit, false, o => o.LlcreateTime, d => d.Lluid == uid);
            var data = iq.Select(d => new Login_History_Response_Dto
            {
                id = d.Llid,
                ip = d.Llip,
                time = d.LlcreateTime.Value.ToString(),
            }).ToList();
            return new Api_Result()
            {
                code = Api_Code.ok,
                message = "ok",
                data = data
            };
        }
        /// <summary>
        /// 通过最后一个code获取用户信息
        /// </summary>
        /// <param name="code"></param>
        /// <param name="ip"></param>
        /// <returns></returns>
        public SysUsers Get_User_By_LastCode(string code, string ip)
        {
           // int.Parse("啊啊啊啊");
            var iq = _login_IOC._sys_Login_Log_EFCore.QueryAll(d => d.Llcode == code && d.Llip == ip);
            if (!iq.Any())
            { 
                return null;
            }
            var log = iq.Single();
            var last = _login_IOC._sys_Login_Log_EFCore.QueryAll(d => d.Lluid == log.Lluid).OrderByDescending(d=>d.LlcreateTime).First();
            if (log.Llcode != last.Llcode)
            {
                return null;
            }
            return _login_IOC._sys_User_EFCore.Find(log.Lluid);
        }


        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public Api_Result Logins(Login_Request_Dto dto)
        {
            var iq = _login_IOC._sys_User_EFCore.QueryAll(d => d.Uaccount == dto.account);
            if (!iq.Any())
            {
                return Result(0, "账号或者密码错误");
            }
            var user=iq.Single();

            if (user.UisBan == 1)
            {
                return Result(0, "账户已被禁用");
            }
            if (user.UisActive == 0)
            {
                return Result(0, "账户未激活", new { active = 1 });
            }

            if (user.Upassword != dto.password.Trim().LoginMd5(user.Usalt))
            {
                return Result(0, "账号或者密码错误");
            }

            //密码验证成功
            SysLoginLogs SysLoginLogs = new SysLoginLogs()
            {
                Llid = Config.GUID(),
                Llcode = dto.code,
                LlcreateTime = DateTime.Now,
                Llexplain = "",
                Llip = Config.GetIp(),
                Llresult = 0,
                Lltype = "Admin",
                Lluid = user.Uid
            };

            _login_IOC._sys_Login_Log_EFCore.Add(SysLoginLogs);
            var result = _login_IOC._sys_Login_Log_EFCore.SaveChanges();
            return Result(result);

        }

        /// <summary>
        /// 重置密码
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public Api_Result Reset_Passwords()
        {
            var data=_login_IOC._sys_User_EFCore.QueryAll().ToList();
            data.ForEach(d => {
                d.Upassword = _configuration["Password:Admin_Init"].LoginMd5(d.Usalt);
            });
            _login_IOC._sys_User_EFCore.updateRange(data);
            var result = _login_IOC._sys_User_EFCore.SaveChanges();
            return Result(result);
        }
    }
}
